package com.happystudy.controller;

import com.happpystudy.model.User;
import com.happpystudy.service.UserService;
import com.happystudy.message.BaseMessageModel;
import com.happystudy.message.ErrorMessage;
import com.happystudy.message.ErrorMessageType;
import com.happystudy.message.SuccessMessage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class AccountInfoController {

    @Resource
    UserService userService;

    @GetMapping("/accountInfo")
    public String returnLoginHtml(HttpServletRequest request){
        //判断是否登录
        HttpSession session = request.getSession(false);
        if (session==null){
            System.out.println("未登录");
            return "login";
        }
        User currentUser = (User) session.getAttribute("currentLoginUser");
        if (currentUser==null){
            System.out.println("有session，但是没有登录信息");
            return "login";
        }
        if ("learner".equalsIgnoreCase(currentUser.getRole())){
            return "accountInfo";
        }else {
            return "accountInfoEductor";
        }
    }

    @PutMapping("/accountInfo/updateInfo")
    @ResponseBody
    public BaseMessageModel updateUserInfo(String key, String value, User user, HttpServletRequest request){
        BaseMessageModel message = new SuccessMessage();
        Integer result = userService.updateUserInfo(key,value,user);
        if (result==-1){
            //返回大学找不到错误
            message = new ErrorMessage(ErrorMessageType.UNIVERSITY_NOT_FOUND_CODE,ErrorMessageType.UNIVERSITY_NOT_FOUND_MSG);
        }
        User updateUser = userService.returnCurrentInfo(user);
        if (updateUser!=null){
            HttpSession session = request.getSession(false);
            if (session!=null){
                session.setAttribute("currentLoginUser",updateUser);
            }else {
                //当前用户未登录
                message = new ErrorMessage(ErrorMessageType.USER_NOT_LOGIN_CODE,ErrorMessageType.USER_NOT_LOGIN_MSG);
            }
        }
        return message;
    }
}
